import axios from 'axios'
import io from 'socket.io-client'
let socket = io('ws://localhost:9093')

// 获取聊天列表
const MSG_LIST = 'MSG_LIST'
// 读取信息
const MSG_RECV = 'MSG_RECV'
// 标示已读
const MSG_READ = 'MSG_READ'

const initState = {
  chatmsg: [],
  users: {},
  unread: 0
}

export function chat(state = initState, action) {
  switch (action.type) {
    case MSG_LIST:
      return {
        ...state,
        chatmsg: action.payload.msgs,
        unread: action.payload.msgs.filter(v => !v.read && v.to === action.payload.userid).length,
        users: action.payload.users
      }
    case MSG_RECV:
      let n = action.payload.to === action.userid ? 1 : 0
      return {
        ...state,
        chatmsg: [...state.chatmsg, action.payload],
        unread: state.unread + n
      }
    case MSG_READ:
      return {
        ...state, chatmsg: state.chatmsg.map(v => {
          if (v.from === action.payload.from && v.to === action.payload.userid && !v.read) {
            v.read = true
          }
          return v
        }),
        unread: state.unread - action.payload.num
      }
    default:
      return state
  }
}

function msgList(msgs, users, userid) {
  return {
    type: MSG_LIST,
    payload: {
      msgs,
      users,
      userid
    }
  }
}

function msgRecv(msg, userid) {
  return {
    type: MSG_RECV,
    payload: msg,
    userid
  }
}

function msgRead({from, userid, num}) {
  return {
    type: MSG_READ,
    payload: {
      from,
      userid,
      num
    }
  }
}

// 首次加载全部消息
export function getMsgList() {
  return (dispatch, getState) => {
    axios.get('/api/user/getmsglist').then(res => {
      if (res.status === 200 && res.data.code === 0) {
        // console.log(getState())
        let userid = getState().user._id // 当前登录用户的 id 用于计算 unread
        dispatch(msgList(res.data.msgs, res.data.users, userid))
      }
    })
  }
}
// 发送消息
export function sendMsg({from, to, msg}) {
  return dispatch => {
    socket.emit('sendmsg', {from, to, msg})
  }
}

// 接收消息
export function recvMsg() {
  return (dispatch, getState) => {
    socket.on('recvmsg', function (data) {
      // console.log('recvmsg', data)
      let userid = getState().user._id
      dispatch(msgRecv(data, userid))
    })
  }
}

// 标记消息为已读，将 from 别人 to 自己的标记为已读
export function readMsg(from) {
  return (dispatch, getState) => {
    axios.post('/api/user/readmsg', {from, }).then(res => {
      if (res.status === 200 && res.data.code === 0) {
        let userid = getState().user._id
        dispatch(msgRead({from, userid, num: res.data.num}))
      }
    })
  }
}